package com.teaching.management.controller;

import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.Student;
import com.teaching.management.entity.User;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 学生控制器
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseRepository courseRepository;

    /**
     * 显示学生仪表盘
     */
    @GetMapping("/dashboard")
    public String showDashboard(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return "redirect:/login";
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return "redirect:/login";
        }

        // 获取学习概览数据
        Map<String, Object> overview = studentService.getStudyOverview(student.getStudentId());

        // 获取学生课程
        List<CourseSelection> selections = studentService.getStudentCourses(student.getStudentId());

        // 获取当前学期的课程
        String currentSemester = student.getGrade();
        List<CourseSelection> currentCourses = selections.stream()
                .filter(c -> currentSemester.equals(c.getSemester()) && "正在修".equals(c.getStatus()))
                .collect(Collectors.toList());

        // 获取当前学期的课程详细信息
        List<Map<String, Object>> currentCoursesWithDetails = currentCourses.stream().map(selection -> {
            Map<String, Object> courseWithDetails = new HashMap<>();
            courseWithDetails.put("selectionId", selection.getSelectionId());
            courseWithDetails.put("studentId", selection.getStudentId());
            courseWithDetails.put("courseId", selection.getCourseId());
            courseWithDetails.put("status", selection.getStatus());
            courseWithDetails.put("score", selection.getScore());
            courseWithDetails.put("semester", selection.getSemester());

            // 添加课程详细信息
            courseRepository.findById(selection.getCourseId()).ifPresent(course -> {
                courseWithDetails.put("courseName", course.getName());
                courseWithDetails.put("credit", course.getCredit());
                courseWithDetails.put("teacherId", course.getTeacherId());
                courseWithDetails.put("classroomId", course.getClassroomId());
                courseWithDetails.put("courseType", course.getCourseType());
            });

            return courseWithDetails;
        }).collect(Collectors.toList());

        // 计算总学分和平均分
        Integer totalCredits = studentService.getTotalCredits(student.getStudentId());
        if (totalCredits == null) {
            totalCredits = 0;
        }

        BigDecimal avgScore = studentService.getAverageScore(student.getStudentId());
        if (avgScore == null) {
            avgScore = BigDecimal.ZERO;
        }

        // 设置模型属性
        model.addAttribute("student", student);
        model.addAttribute("overview", overview);
        model.addAttribute("courseSelections", selections);
        model.addAttribute("currentCourses", currentCoursesWithDetails);
        model.addAttribute("totalCredits", totalCredits);
        model.addAttribute("averageScore", avgScore);
        model.addAttribute("currentCourseCount", currentCourses.size());

        return "student/dashboard";
    }

    /**
     * 选课中心页面
     */
    @GetMapping("/courses")
    public String showCourses(HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return "redirect:/login";
        }

        return "student/courses";
    }

    /**
     * 我的课表页面
     */
    @GetMapping("/schedule")
    public String showSchedule(HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return "redirect:/login";
        }

        return "student/schedule";
    }

    /**
     * 我的成绩页面
     */
    @GetMapping("/grades")
    public String showGrades(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return "redirect:/login";
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return "redirect:/login";
        }

        // 获取学生成绩
        List<CourseSelection> courseSelections = studentService.getStudentCourses(student.getStudentId());
        model.addAttribute("courseSelections", courseSelections);

        return "student/grades";
    }

    /**
     * 个人信息页面
     */
    @GetMapping("/profile")
    public String showProfile(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return "redirect:/login";
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        model.addAttribute("student", student);

        return "student/profile";
    }
}